<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\dic\DicProduct;
use app\dic\DicPublic;
use think\App;
use think\facade\Db;
use util\Excel;

use think\exception\ValidateException;
use think\facade\Log;
use util\Token;

/**
 * Product控制器
 */
class Product extends AdminBase
{

    protected $model = null;
    protected $token = null;
    protected $admin_values = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Product();

        $this->validate = \app\admin\validate\Product::class;
        $this->token = $this->request->header('token');
        $adminId = Token::userId($this->token);
        $this->adminId = $adminId;
        $admin = table('system_admin')->select()->toarray();
        $this->admin_values = array_column($admin, 'nickname', 'id');
    }


    /**
     * 列表
     */
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        if (!empty($filters['product_status'])) {
            $where[] = array('tags', 'LIKE', '%' . $filters['product_status'] . '%');
        }
        $where['site_id'] = 37;
        $where['status'] = DicProduct::$product_status_active;
        // halt($where);
        $list = $this->model
            ->where($where)
            ->where(function ($query) use ($filters) {
                if (!empty($filters['product_tags'])) {
                    foreach ($filters['product_tags'] as $k => $v) {
                        if ($k == 0) {
                            $query->where('tags', 'LIKE', '%' . $v . '%');
                        } else {
                            $query->whereor('tags', 'LIKE', '%' . $v . '%');
                        }
                    }
                }
            })
            // ->order('brand desc')
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $lists[$k]['is_tf'] = $this->is_tf($v['brand']);
            //投放开发人员
            //通过brand查询产品信息表中的开发人员
            $dev_admin = table('product_info')->where(['brand' => strtolower($v['brand'])])->find();
            //查询在投人数
            $lists[$k]['dev_admin'] = !empty($dev_admin['dev_admin']) ? $this->admin_values[$dev_admin['dev_admin']] : '';
            $lists[$k]['tf_num'] = $this->tf_num($v['brand']);
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];

        return json($data);
    }

    //显示投放状态
    public function is_tf($brand)
    {
        //2新品保护期 产品信息表设置新品保护期开始时间
        $time = table('product_info')->where(['brand' => strtolower($brand)])->find();
        //新品时间
        $xp_time = !empty($time['xp_time']) ? $time['xp_time'] : 0;
        //爆品时间
        $bp_time = !empty($time['bp_time']) ? $time['bp_time'] : 0;
        //当前时间和新品保护期时间比较，大于则不可申请
        $xpend_time = strtotime('+3 month', $xp_time);
        $bpend_time = strtotime('+1 month', $bp_time);
        if (time() < $xpend_time) {
            return '新品保护期';
        }
        if (time() < $bpend_time) {
            return '爆品保护期';
        }
        $num = table('tfrecord')->where(['apply_status' => 1, 'tf_status' => 1, 'tf_admin' => $this->adminId])->count();
        if ($num == 3 || $num > 3) {
            return '受限';
        }
        //通过brand查询是否可以投放
        $num = table('tfrecord')->where(['apply_status' => 1, 'tf_status' => 1, 'brand' => strtolower($brand)])->count();
        if ($num == 3 || $num > 3) {
            return '已满';
        }
        return '可投';
    }

    //查询投放人数
    public function tf_num($brand)
    {

        //2新品保护期 产品信息表设置新品保护期开始时间
        $time = table('product_info')->where(['brand' => strtolower($brand)])->find();
        //新品时间
        $xp_time = !empty($time['xp_time']) ? $time['xp_time'] : 0;
        //爆品时间
        $bp_time = !empty($time['bp_time']) ? $time['bp_time'] : 0;
        //当前时间和新品保护期时间比较，大于则不可申请
        $xpend_time = strtotime('+3 month', $xp_time);
        $bpend_time = strtotime('+1 month', $bp_time);
        if (time() < $xpend_time) {
            return '-';
        }
        if (time() < $bpend_time) {
            return '-';
        }
        //通过时间段查询在投人数
        $tf_num = table('tfrecord')->where(['apply_status' => 1, 'tf_status' => 1, 'brand' => strtolower($brand)])->count();
        return $tf_num;
    }

    //查询投放详情,条件为审核通过的列表
    public function tf_list()
    {
        $post = $this->request->post();
        $record = table('tfrecord')->where(['brand' => strtolower($post['brand']), 'apply_status' => 1, 'tf_status' => 1])->select()->toarray();
        foreach ($record as $k => $v) {
            //在投人员
            if (isset($this->admin_values[$v['tf_admin']]) && !empty($this->admin_values[$v['tf_admin']])) {
                $record[$k]['tf_admin'] =  $this->admin_values[$v['tf_admin']];
            } else {
                $record[$k]['tf_admin'] =  0;
            }
            $record[$k]['check_time'] = !empty($v['check_time']) ? date('Y-m-d', $v['check_time']) : '';
            $record[$k]['tf_status'] =  $v['tf_status'] == 1 ? '在投' : '无效';
            // $record[$k]['apply_status'] = $v['apply_status'] != 0 ? $this->tf_status($v['apply_status']) : '待审核';
            //出单时间
            $record[$k]['cd_time'] =  date('Y-m-d H:i:s', time());
            $record[$k]['roi'] =  0;
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $record,
        ];
        return json($data);
    }



    public function tf_status($status)
    {
        $apply_status = ['待审核', '审核通过', '审核不通过'];
        return  !empty($apply_status[$status]) ? $apply_status[$status] : '';
    }


    //同步商品到店铺
    public function product_to_shopify()
    {
        $return_data = [
            'code' => 1,
            'msg' => '',
            'data' => [],
        ];
        $post = $this->request->post();
        $site_id = $post['site_id'] ? $post['site_id'] : 19;
        // $site_id =  19;
        $switch = $post['switch'] ? $post['switch'] : 0;
        $product_id = $post['product_id'] ? $post['product_id'] : 8013362430171;
        $product = table('product')
            ->where('id', $product_id)
            ->find();
        if (!empty($product)) {
            $site = table('site')
                ->where('id', $product['site_id'])
                ->find();
            $url = $site['site_url'] . "/admin/api/2022-10/products/" . $product['id'] . ".json";
            $ldata =  geturl($url, $site['apikey'], $site['apisecret']);
            $larr = array();
            if ($ldata) {
                $ldata2 = json_decode($ldata, true);
                if (!empty($ldata2['product'])) {
                    $lproduct = $ldata2['product'];
                    if ($switch == 1) {
                        $larr = $this->switch($lproduct, $post);
                    } else {
                        $larr['title'] = $lproduct['title'];
                        $larr['body_html'] = $lproduct['body_html'];
                        $larr['vendor'] = $lproduct['vendor'];
                        $larr['product_type'] = $lproduct['product_type'];
                        $larr['tags'] = $lproduct['tags'];
                        $larr['status'] = DicProduct::$product_status_draft;
                        $larr['variants'] = array();
                        $larr['options'] = array();
                        $larr['images'] = array();

                        //商品SKU
                        if (!empty($post['tableData'])) {
                            foreach ($post['tableData'] as $tableData) {
                                $avariants = array();
                                // SKU转小写
                                $avariants['sku'] = $tableData['sku'];
                                $avariants['title'] = $tableData['name'];
                                $avariants['option1'] = $tableData['option1'];
                                if ($tableData['option2'] == '-') {
                                    $avariants['option2'] = $tableData['option3'];
                                } else {
                                    $avariants['option2'] = $tableData['option2'];
                                    $avariants['option3'] = $tableData['option3'];
                                }
                                if ($tableData['option3'] == '-') {
                                } else {
                                    $avariants['option3'] = $tableData['option3'];
                                }
                                $larr['variants'][] = $avariants;
                            }
                        }
                        //商品属性
                        if (!empty($post['color'])) {
                            $aoptions = array();
                            $aoptions['name'] = 'color';
                            $aoptions['values'] = implode(',', $post['color']);
                            $larr['options'][] = $aoptions;
                        }
                        if (!empty($post['size'])) {
                            $aoptions = array();
                            $aoptions['name'] = 'size';
                            $aoptions['values'] = implode(',', $post['size']);
                            $larr['options'][] = $aoptions;
                        }
                        if (!empty($post['cup'])) {
                            $aoptions = array();
                            $aoptions['name'] = 'cup';
                            $aoptions['values'] = implode(',', $post['cup']);
                            $larr['options'][] = $aoptions;
                        }
                        if (!empty($lproduct['images'])) {
                            foreach ($lproduct['images'] as $vimages) {
                                $aimages = array();
                                $aimages['src'] = $vimages['src'];
                                $larr['images'][] = $aimages;
                            }
                        }
                    }
                }
            }
            $msgs = '';
            if (!empty($larr)) {
                $iscustom2 = table('site')
                    ->where('id', $site_id)
                    ->find();
                $url2 = $iscustom2['site_url'] . "/admin/api/2022-10/products.json";
                if ($switch == 1) {
                    foreach ($post['color'] as $k => $v) {
                        $newdata['product'] = $larr[$k];
                        $newreturn = posturl($url2, $newdata, $iscustom2);
                        if (!empty($newreturn)) {
                            $datareturn = json_decode($newreturn, true);
                            if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                                if (!empty($msgs)) {
                                    $msgs = $msgs . ',' . $datareturn['product']['id'];
                                } else {
                                    $msgs = $datareturn['product']['id'];
                                }
                            } else {
                                $newreturn = json_decode($newreturn, true);
                                $return_data['msg'] = $newreturn['errors']['base'][0];
                                return json($return_data);
                            }
                        }
                    }
                } else {
                    $newdata['product'] = $larr;
                    $newreturn = posturl($url2, $newdata, $iscustom2);
                    if (!empty($newreturn)) {
                        $datareturn = json_decode($newreturn, true);
                        if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                            $msgs = $datareturn['product']['id'];
                        } else {
                            $newreturn = json_decode($newreturn, true);
                            $return_data['msg'] = $newreturn['errors']['base'][0];
                            return json($return_data);
                        }
                    }
                }
            }
            $return_data['data'] = $msgs;
        }
        return json($return_data);
    }

    /**
     * 多产品
     * @param array params
     */
    public function switch($lproduct, $post)
    {
        $larr_new = array();
        foreach ($post['color'] as $kcolor => $vcolor) {
            $larr = array();
            $larr['title'] = $lproduct['title'];
            $larr['body_html'] = $lproduct['body_html'];
            $larr['vendor'] = $lproduct['vendor'];
            $larr['product_type'] = $lproduct['product_type'];
            $larr['tags'] = $lproduct['tags'];
            $larr['status'] = DicProduct::$product_status_draft;
            $larr['variants'] = array();
            $larr['options'] = array();
            $larr['images'] = array();
            //商品SKU
            if (!empty($post['tableData'])) {
                foreach ($post['tableData'] as $tableData) {
                    if ($tableData['option1'] == $vcolor) {
                        $avariants = array();
                        // SKU转小写
                        $avariants['sku'] = $tableData['sku'];
                        $avariants['title'] = $tableData['name'];
                        $avariants['option1'] = $tableData['option1'];
                        if ($tableData['option2'] == '-') {
                            $avariants['option2'] = $tableData['option3'];
                        } else {
                            $avariants['option2'] = $tableData['option2'];
                            $avariants['option3'] = $tableData['option3'];
                        }
                        if ($tableData['option3'] == '-') {
                        } else {
                            $avariants['option3'] = $tableData['option3'];
                        }
                        $larr['variants'][] = $avariants;
                    }
                }
            }
            //商品属性
            if (!empty($vcolor)) {
                $aoptions = array();
                $aoptions['name'] = 'color';
                $aoptions['values'] = $vcolor;
                $larr['options'][] = $aoptions;
            }
            if (!empty($post['size'])) {
                $aoptions = array();
                $aoptions['name'] = 'size';
                $aoptions['values'] = implode(',', $post['size']);
                $larr['options'][] = $aoptions;
            }
            if (!empty($post['cup'])) {
                $aoptions = array();
                $aoptions['name'] = 'cup';
                $aoptions['values'] = implode(',', $post['cup']);
                $larr['options'][] = $aoptions;
            }
            if (!empty($lproduct['images'])) {
                foreach ($lproduct['images'] as $vimages) {
                    $aimages = array();
                    $aimages['src'] = $vimages['src'];
                    $larr['images'][] = $aimages;
                }
            }
            if (!empty($larr)) {
                $larr_new[] = $larr;
            }
        }
        return $larr_new;
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->scene('edit')->check($post);
                //修改tags格式
                $post['tags'] = implode(',', $post['tags']);
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }

        //详情修改
        if (!empty($row['tags'])) {
            $row['tags'] = explode(',', $row['tags']);
        }
        if (!empty($row['images2'])) {
            $row['images2'] = json_decode($row['images2'], true);
            $images = array();
            foreach ($row['images2'] as $k => $v) {
                $images[] = $v['src'];
            }
            $row['images2'] = $images;
        }
        if (!empty($row['options'])) {
            $row['options'] = json_decode($row['options'], true);
        }
        $productvariants = table('productvariants')->where(['product_id' => $row['id']])->select();
        if (!empty($productvariants)) {
            $row['productvariants'] = $productvariants;
        } else {
            $row['productvariants'] = array();
        }
        return success('ok', $row);
    }

    /**
     * 查找
     */
    public function find()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        //详情修改
        if (!empty($row['tags'])) {
            $row['tags'] = explode(',', $row['tags']);
        }
        if (!empty($row['images2'])) {
            $row['images2'] = json_decode($row['images2'], true);
            $images = array();
            foreach ($row['images2'] as $k => $v) {
                $images[] = $v['src'];
            }
            $row['images2'] = $images;
        }
        if (!empty($row['options'])) {
            $row['options'] = json_decode($row['options'], true);
        }
        $productvariants = table('productvariants')->where(['product_id' => $row['id']])->select();
        if (!empty($productvariants)) {
            $row['productvariants'] = $productvariants;
        } else {
            $row['productvariants'] = array();
        }
        return success('ok', $row);
    }

    /**
     * 复制产品
     */

    public function  copy_product_to_shopify()
    {
        $post = $this->request->post();
        $site_id = $post['site_id'] ? $post['site_id'] : 19;
        if (!empty($post['product_id'])) {
            $product_id = explode(',', $post['product_id']);
        } else {
            $return_data = [
                'code' => 1,
                'msg' => '',
                'data' => [],
            ];
            return json($return_data);
        }
        foreach ($product_id as $k => $v) {
            $return_data = [
                'code' => 1,
                'msg' => '',
                'data' => [],
            ];
            $product = table('product')
                ->where('id', $v)
                ->find();
            if (!empty($product)) {
                $site = table('site')
                    ->where('id', $product['site_id'])
                    ->find();
                $url = $site['site_url'] . "/admin/api/2022-10/products/" . $product['id'] . ".json";
                $ldata =  geturl($url, $site['apikey'], $site['apisecret']);
                $larr = array();
                if ($ldata) {
                    $ldata2 = json_decode($ldata, true);
                    if (!empty($ldata2['product'])) {
                        $lproduct = $ldata2['product'];
                        $larr['title'] = $lproduct['title'];
                        $larr['body_html'] = $lproduct['body_html'];
                        $larr['vendor'] = $lproduct['vendor'];
                        $larr['product_type'] = $lproduct['product_type'];
                        $larr['tags'] = $lproduct['tags'];
                        $larr['status'] = DicProduct::$product_status_draft;
                        $larr['variants'] = array();
                        $larr['options'] = array();
                        $larr['images'] = array();
                        //商品SKU
                        if (!empty($lproduct['variants'])) {
                            foreach ($lproduct['variants'] as $tableData) {
                                $avariants = array();
                                // SKU转小写
                                $avariants['sku'] = $tableData['sku'];
                                $avariants['title'] = $tableData['title'];
                                $avariants['option1'] = $tableData['option1'];
                                $avariants['option2'] = $tableData['option2'];
                                $avariants['option3'] = $tableData['option3'];
                                $larr['variants'][] = $avariants;
                            }
                        }
                        if (!empty($lproduct['options'])) {
                            foreach ($lproduct['options'] as $options) {
                                $aoptions = array();
                                $aoptions['name'] = $options['name'];
                                $aoptions['values'] = implode(',', $options['values']);
                                $larr['options'][] = $aoptions;
                            }
                        }
                        if (!empty($lproduct['images'])) {
                            foreach ($lproduct['images'] as $vimages) {
                                $aimages = array();
                                $aimages['src'] = $vimages['src'];
                                $larr['images'][] = $aimages;
                            }
                        }
                    }
                }
                $msgs = '';
                if (!empty($larr)) {
                    $iscustom2 = table('site')
                        ->where('id', $site_id)
                        ->find();
                    $url2 = $iscustom2['site_url'] . "/admin/api/2022-10/products.json";

                    $newdata['product'] = $larr;
                    $newreturn = posturl($url2, $newdata, $iscustom2);
                    if (!empty($newreturn)) {
                        $datareturn = json_decode($newreturn, true);
                        if (isset($datareturn['product']['id']) && !empty($datareturn['product']['id'])) {
                            $msgs = $datareturn['product']['id'];
                        } else {
                            $newreturn = json_decode($newreturn, true);
                            $return_data['msg'] = $newreturn['errors']['base'][0];
                            return json($return_data);
                        }
                    }
                }
                $return_data['data'] = $msgs;
            }
        }
        return json($return_data);
    }
}
